<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\scanwork\Config as ConfigModel;
use think\Db;
use think\Request;
use fast\Random;

class Wbgs extends Api
{
    protected $noNeedLogin = ['login', 'bindMember'];
    protected $noNeedRight = ['*'];
    protected $userInfo = null;

    /**
     * 初始化方法
     */
    protected function _initialize()
    {
        parent::_initialize();
        // 获取当前登录用户信息
        if ($this->auth->isLogin()) {
            $this->userInfo = $this->auth->getUserinfo();
        }
    }

    /**
     * 微信小程序登录
     */
    public function login()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('缺少登录凭证', null, 401);
        }

        // 获取微信用户信息
        $wxUser = $this->getWxSession($code);
        if (!$wxUser || isset($wxUser['errcode'])) {
            $this->error('微信登录失败: ' . ($wxUser['errmsg'] ?? '未知错误'), null, 401);
        }

        // 查找或创建用户
        $user = Db::name('user')->where('wechat_openid', $wxUser['openid'])->find();
        if (!$user) {
            // 创建新用户
            $username = 'wxuser_' . Random::alnum(10);
            $password = Random::alnum(16);
            $userData = [
                'username' => $username,
                'nickname' => '微信用户' . substr($wxUser['openid'], 0, 8),
                'password' => md5($password),
                'wechat_openid' => $wxUser['openid'],
                'wechat_session_key' => $wxUser['session_key'],
                'avatar' => '',
                'createtime' => time(),
                'updatetime' => time(),
                'status' => 'normal'
            ];
            $userId = Db::name('user')->insertGetId($userData);
            $user = Db::name('user')->where('id', $userId)->find();
        }

        // 登录用户
        $this->auth->direct($user['id']);
        $token = $this->auth->getToken();
        
        $this->success('登录成功', [
            'token' => $token,
            'user' => $user
        ]);
    }

    /**
     * 获取微信session
     */
    private function getWxSession($code)
    {
        // 从配置系统获取小程序appid和secret
        $appid = ConfigModel::getMiniappAppid();
        $secret = ConfigModel::getMiniappSecret();
        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $result = file_get_contents($url);
        return json_decode($result, true);
    }

    /**
     * 修改用户信息
     */
    public function updateProfile()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $username = $this->request->post('username', $user['username']);
        $nickname = $this->request->post('nickname', $user['nickname']);
        
        // 检查用户名是否已存在
        if ($username != $user['username']) {
            $exist = Db::name('user')->where('username', $username)->where('id', '<>', $user['id'])->find();
            if ($exist) {
                $this->error('用户名已存在');
            }
        }
        
        $data = [
            'username' => $username,
            'nickname' => $nickname,
            'updatetime' => time()
        ];
        
        // 如果需要修改密码
        $password = $this->request->post('password');
        if ($password) {
            $data['password'] = md5($password);
        }
        
        Db::name('user')->where('id', $user['id'])->update($data);
        
        // 更新用户信息
        $this->auth->autoLogin(Db::name('user')->where('id', $user['id'])->find());
        
        $this->success('更新成功', [
            'user' => $this->auth->getUserinfo()
        ]);
    }

    /**
     * 绑定fastadmin会员
     */
    public function bindMember()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        
        if (!$username || !$password) {
            $this->error('用户名和密码不能为空');
        }
        
        // 查找用户
        $user = Db::name('user')->where('username', $username)->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        // 验证密码
        if (md5($password) != $user['password']) {
            $this->error('密码错误');
        }
        
        // 获取当前微信用户
        $wxCode = $this->request->post('wx_code');
        if (!$wxCode) {
            $this->error('缺少微信登录凭证');
        }
        
        $wxUser = $this->getWxSession($wxCode);
        if (!$wxUser || isset($wxUser['errcode'])) {
            $this->error('微信登录失败');
        }
        
        // 更新用户信息，绑定微信
        $updateData = [
            'wechat_openid' => $wxUser['openid'],
            'wechat_session_key' => $wxUser['session_key'],
            'updatetime' => time()
        ];
        
        Db::name('user')->where('id', $user['id'])->update($updateData);
        
        // 登录用户
        $this->auth->direct($user['id']);
        $token = $this->auth->getToken();
        
        $this->success('绑定成功', [
            'token' => $token,
            'user' => $this->auth->getUserinfo()
        ]);
    }

    /**
     * 获取用户信息
     */
    public function userInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $this->success('获取成功', $user);
    }

    /**
     * 获取任务列表
     */
    public function getWorkTasks()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $workerId = $user['id'];
        
        $tasks = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('a.createtime desc')
            ->select();
            
        $this->success('获取成功', $tasks);
    }

    /**
     * 获取报工任务详情
     */
    public function getWorkTaskDetail()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $allocationId = $this->request->param('id');
        
        if (!$allocationId) {
            $this->error('未指定任务ID');
        }
        
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $user['id'])
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
            
        if (!$allocation) {
            $this->error('任务不存在或不属于当前用户');
        }
        
        $this->success('获取成功', $allocation);
    }

    /**
     * 提交报工
     */
    public function submitWorkReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $allocationId = $this->request->post('allocation_id');
        $quantity = $this->request->post('quantity');
        $remark = $this->request->post('remark');
        
        if (!$allocationId || !$quantity) {
            $this->error('参数不完整');
        }
        
        $allocation = Db::name('scanwork_allocation')->where('id', $allocationId)->where('user_id', $user['id'])->find();
        if (!$allocation) {
            $this->error('任务不存在或不属于当前用户');
        }
        
        if ($allocation['status'] != 0) {
            $this->error('任务已完成，无法重复报工');
        }
        
        // 获取工序工价
        $processPrice = Db::name('scanwork_process_price')
            ->where('model_id', $allocation['model_id'])
            ->where('process_id', $allocation['process_id'])
            ->find();
            
        if (!$processPrice) {
            $this->error('工序工价记录未找到');
        }
        
        $wage = $quantity * $processPrice['price'];
        $reportData = [
            'allocation_id' => $allocationId,
            'user_id' => $user['id'],
            'quantity' => $quantity,
            'wage' => $wage,
            'remark' => $remark,
            'status' => 0,
            'createtime' => time()
        ];
        
        $reportId = Db::name('scanwork_report')->insertGetId($reportData);
        if (!$reportId) {
            $this->error('报工失败');
        }
        
        // 更新任务状态
        Db::name('scanwork_allocation')->where('id', $allocationId)->update(['status' => 1]);
        
        $this->success('报工成功', ['report_id' => $reportId]);
    }

    /**
     * 上传报工图片
     */
    public function uploadWorkImage()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $reportId = $this->request->post('report_id');
        
        if (!$reportId) {
            $this->error('缺少报工ID');
        }
        
        if (!empty($_FILES['file'])) {
            $file = $_FILES['file'];
            if ($file['error'] == 0) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = date('YmdHis') . '_' . Random::alnum(8) . '.' . $ext;
                $dateDir = date('Y-m-d');
                $uploadDir = 'uploads/baogong/' . $dateDir . '/';
                
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $filepath = $uploadDir . $filename;
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    Db::name('scanwork_report_image')->insert([
                        'report_id' => $reportId,
                        'image_url' => '/uploads/baogong/' . $dateDir . '/' . $filename,
                        'createtime' => time()
                    ]);
                    
                    $this->success('上传成功', ['url' => '/uploads/baogong/' . $dateDir . '/' . $filename]);
                } else {
                    $this->error('文件上传失败');
                }
            } else {
                $this->error('文件上传错误');
            }
        } else {
            $this->error('未接收到文件');
        }
    }

    /**
     * 获取报工记录
     */
    public function getWorkRecords()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        // 查询报工记录
        $records = Db::name('scanwork_report')
            ->where('user_id', $user['id'])
            ->order('createtime desc')
            ->select();
        
        // 补充详细信息
        foreach ($records as &$record) {
            // 获取分配信息
            $allocation = Db::name('scanwork_allocation')->where('id', $record['allocation_id'])->find();
            if ($allocation) {
                // 获取订单信息
                $order = Db::name('scanwork_order')->where('id', $allocation['order_id'])->find();
                $record['order_no'] = $order ? $order['order_no'] : '';
                
                // 获取型号信息
                $model = Db::name('scanwork_model')->where('id', $allocation['model_id'])->find();
                $record['model_name'] = $model ? $model['name'] : '';
                
                // 获取产品信息
                if ($model) {
                    $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
                    $record['product_name'] = $product ? $product['name'] : '';
                } else {
                    $record['product_name'] = '';
                }
                
                // 获取工序信息
                $process = Db::name('scanwork_process')->where('id', $allocation['process_id'])->find();
                $record['process_name'] = $process ? $process['name'] : '';
            } else {
                $record['order_no'] = '';
                $record['model_name'] = '';
                $record['product_name'] = '';
                $record['process_name'] = '';
            }
            
            // 获取图片
            $images = Db::name('scanwork_report_image')
                ->where('report_id', $record['id'])
                ->field('image_url')
                ->select();
                
            $record['images'] = array_map(function($img) {
                return ConfigModel::getSiteDomain() . $img['image_url'];
            }, $images);
        }
        
        $this->success('获取成功', $records);
    }

    /**
     * 获取工资统计
     */
    public function getSalaryData()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $month = $this->request->param('month', date('Y-m'));
        $startTime = strtotime($month . '-01 00:00:00');
        $endTime = strtotime($month . '-' . date('t', $startTime) . ' 23:59:59');
        
        $wages = Db::name('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('r.user_id', $user['id'])
            ->where('r.status', 1)
            ->where('r.createtime', 'between', [$startTime, $endTime])
            ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('r.createtime desc')
            ->select();
            
        $totalWage = array_sum(array_column($wages, 'wage'));
        
        $this->success('获取成功', [
            'wages' => $wages,
            'totalWage' => $totalWage,
            'month' => $month
        ]);
    }
    
    /**
     * 扫码报工
     */
    public function scanQRCode()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $qrCode = $this->request->post('qr_code');
        
        if (!$qrCode) {
            $this->error('缺少二维码数据');
        }
        
        // 这里需要根据实际的二维码格式解析出任务ID
        // 假设二维码内容就是任务ID
        $allocationId = $qrCode;
        
        $allocation = Db::name('scanwork_allocation')
            ->where('id', $allocationId)
            ->where('user_id', $user['id'])
            ->find();
            
        if (!$allocation) {
            $this->error('任务不存在或不属于当前用户');
        }
        
        if ($allocation['status'] != 0) {
            $this->error('任务已完成');
        }
        
        // 获取详细信息
        $order = Db::name('scanwork_order')->where('id', $allocation['order_id'])->find();
        $model = Db::name('scanwork_model')->where('id', $allocation['model_id'])->find();
        $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
        $process = Db::name('scanwork_process')->where('id', $allocation['process_id'])->find();
        
        // 计算已报数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 'in', [0, 1])
            ->sum('quantity');
            
        $remainingQuantity = $allocation['quantity'] - $reportedQuantity;
        
        $taskInfo = [
            'id' => $allocation['id'],
            'order_no' => $order ? $order['order_no'] : '',
            'product_name' => $product ? $product['name'] : '',
            'model_name' => $model ? $model['name'] : '',
            'process_name' => $process ? $process['name'] : '',
            'remaining_quantity' => $remainingQuantity
        ];
        
        $this->success('获取成功', $taskInfo);
    }
    
    /**
     * 获取今日统计数据
     */
    public function getTodayStats()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        // 获取今日任务数
        $todayTaskCount = Db::name('scanwork_allocation')
            ->where('user_id', $user['id'])
            ->where('createtime', '>=', strtotime('today'))
            ->count();
        
        // 获取今日报工数
        $todayReportCount = Db::name('scanwork_report')
            ->where('user_id', $user['id'])
            ->where('createtime', '>=', strtotime('today'))
            ->count();
        
        // 获取今日工资
        $todayWage = Db::name('scanwork_report')
            ->where('user_id', $user['id'])
            ->where('createtime', '>=', strtotime('today'))
            ->sum('amount');
        
        $stats = [
            'taskCount' => $todayTaskCount,
            'reportCount' => $todayReportCount,
            'wage' => $todayWage
        ];
        
        $this->success('获取成功', $stats);
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $this->auth->logout();
        $this->success('退出成功');
    }
}